<template>
  <el-button :disabled="!btnEnable" @click="sendcode">
    {{btnText}}
  </el-button>
</template>
<script>

export default {
  name: 'CodeButton',
  data () {
    return {
      btnEnable: true,
      btnText: '获取验证码'
    }
  },
  mounted() {

  },
  props: {
    type:{
      type: String,
      default: 'login'
    },
    mobile:{
      type: String,
      default: ''
    },
  },
  methods: {
    sendcode() {
      if (this.mobile.length==0) {
        this.$emit('setError', '手机号码不能为空')
      } else if (!this.mobile.match(/^(?:0?1)[123456789]\d{9}$/)) {
        this.$emit('setError', '手机号码格式错误')
      } else {
        this.$emit('setError', '')
        //发送验证码
        this.btnEnable = false
        this.$api.post('/app/user/auth/sendCode',
          {
            mobile: this.mobile,
            type: this.type
          }
        ).then((response) => {
          if (response.code !== 0) {
            this.$emit('setError', response.msg)
          }
        })

        var time = 60
        this.btnText = time + '秒'
        var codeTime = setInterval(() => {
          if (time == 1) {
            clearInterval(codeTime)
            this.btnEnable = true
            this.btnText = '获取验证码'
            return true
          }
          time = time - 1
          this.btnText = time + '秒'
        }, 1000);
      }
    },
  }
}
</script>
<style scoped>

</style>
